import tkinter as tk
from tkinter import messagebox

# 自定义哈希表
class HashTable:
    def __init__(self, size=10):
        self.size = size
        self.buckets = [[] for _ in range(size)]

    def hash_function(self, key):
        return hash(key) % self.size

    def insert(self, key, value):
        index = self.hash_function(key)
        bucket = self.buckets[index]
        for i, (k, v) in enumerate(bucket):
            if k == key:
                bucket[i] = (key, value)
                return
        bucket.append((key, value))

    def get(self, key):
        index = self.hash_function(key)
        bucket = self.buckets[index]
        for k, v in bucket:
            if k == key:
                return v
        raise KeyError(f"Key '{key}' not found")

    def remove(self, key):
        index = self.hash_function(key)
        bucket = self.buckets[index]
        for i, (k, v) in enumerate(bucket):
            if k == key:
                del bucket[i]
                return
        raise KeyError(f"Key '{key}' not found")


# 定义学生类
class Student:
    def __init__(self, username, full_name, age, school, interests, relations, followed_courses):
        self.username = username
        self.full_name = full_name
        self.age = age
        self.school = school
        self.interests = interests
        self.relations = relations
        self.followed_courses = followed_courses
        self.communities = []

    def add_friend(self, friend_username):
        if friend_username not in self.relations:
            self.relations.append(friend_username)

    def join_community(self, community_name):
        if community_name not in self.communities:
            self.communities.append(community_name)

    def leave_community(self, community_name):
        if community_name in self.communities:
            self.communities.remove(community_name)


# 定义社区类
class Community:
    def __init__(self, name, description, topic):
        self.name = name
        self.description = description
        self.topic = topic
        self.members = []

    def add_member(self, username):
        if username not in self.members:
            self.members.append(username)

    def remove_member(self, username):
        if username in self.members:
            self.members.remove(username)


# 社交网络应用类
class SocialNetworkApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Social Network System")

        # 使用哈希表存储学生和社区
        self.students = HashTable()
        self.communities = HashTable()

        # 初始化学生数据
        student_data = [
            {
                "username": "thomas_dubois",
                "fullName": "Thomas Dubois",
                "age": 21,
                "school": "Chang'an University",
                "interests": ["programming", "video games", "basketball"],
                "relations": ["emma_martin", "lucas_bernard"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "emma_martin",
                "fullName": "Emma Martin",
                "age": 20,
                "school": "Chang'an University",
                "interests": ["literature", "photography", "travel"],
                "relations": ["thomas_dubois", "camille_petit"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "lucas_bernard",
                "fullName": "Lucas Bernard",
                "age": 22,
                "school": "Chang'an University",
                "interests": ["mathematics", "chess", "piano"],
                "relations": ["thomas_dubois", "alexandre_dupont"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "camille_petit",
                "fullName": "Camille Petit",
                "age": 19,
                "school": "Chang'an University",
                "interests": ["politics", "debates", "journalism"],
                "relations": ["emma_martin", "julie_moreau", "nicolas_leroy", "lucas_bernard"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "alexandre_dupont",
                "fullName": "Alexandre Dupont",
                "age": 21,
                "school": "Chang'an University",
                "interests": ["statistics", "economics", "tennis"],
                "relations": ["lucas_bernard"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "julie_moreau",
                "fullName": "Julie Moreau",
                "age": 20,
                "school": "Chang'an University",
                "interests": ["painting", "sculpture", "art history"],
                "relations": ["camille_petit", "sophie_lambert"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "nicolas_leroy",
                "fullName": "Nicolas Leroy",
                "age": 23,
                "school": "Chang'an University",
                "interests": ["artificial intelligence", "robotics", "science fiction"],
                "relations": ["alexandre_dupont", "hugo_durand"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "sophie_lambert",
                "fullName": "Sophie Lambert",
                "age": 21,
                "school": "Chang'an University",
                "interests": ["finance", "entrepreneurship", "travel"],
                "relations": ["julie_moreau", "paul_mercier", "hugo_durand"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "antoine_blanc",
                "fullName": "Antoine Blanc",
                "age": 22,
                "school": "Chang'an University",
                "interests": ["classical music", "composition", "violin"],
                "relations": ["chloe_rousseau", "laura_fournier"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "chloe_rousseau",
                "fullName": "Chloé Rousseau",
                "age": 20,
                "school": "Chang'an University",
                "interests": ["sustainable development", "engineering", "hiking"],
                "relations": ["antoine_blanc", "manon_lefevre", "hugo_durand"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "paul_mercier",
                "fullName": "Paul Mercier",
                "age": 21,
                "school": "Chang'an University",
                "interests": ["international relations", "languages", "history"],
                "relations": ["sophie_lambert", "maxime_simon"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "laura_fournier",
                "fullName": "Laura Fournier",
                "age": 19,
                "school": "Chang'an University",
                "interests": ["economics", "dance", "cinema"],
                "relations": ["antoine_blanc", "hugo_durand", "antoine_blanc"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "hugo_durand",
                "fullName": "Hugo Durand",
                "age": 22,
                "school": "Chang'an University",
                "interests": ["quantum physics", "astronomy", "science fiction"],
                "relations": ["nicolas_leroy", "laura_fournier"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "manon_lefevre",
                "fullName": "Manon Lefèvre",
                "age": 20,
                "school": "Chang'an University",
                "interests": ["marketing", "fashion", "cooking"],
                "relations": ["chloe_rousseau", "maxime_simon", "antoine_blanc"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            },
            {
                "username": "maxime_simon",
                "fullName": "Maxime Simon",
                "age": 21,
                "school": "Chang'an University",
                "interests": ["architecture", "design", "photography"],
                "relations": ["paul_mercier", "manon_lefevre"],
                "followed_courses": ["CS101", "MATH201", "CS250"]
            }
        ]

        for data in student_data:
            student = Student(
                username=data["username"],
                full_name=data["fullName"],
                age=data["age"],
                school=data["school"],
                interests=data["interests"],
                relations=data["relations"],
                followed_courses=data["followed_courses"]
            )
            self.students.insert(student.username, student)

        # 初始化社区数据
        self.communities.insert("Programmers", Community(name="Programmers", description="A community for coding enthusiasts.", topic="programming"))
        self.communities.insert("Photographers", Community(name="Photographers", description="A community for photography lovers.", topic="photography"))

        # 创建GUI组件
        self.create_widgets()

    def find_student_by_username(self, username):
        try:
            return self.students.get(username)
        except KeyError:
            return None

    def find_community_by_name(self, name):
        try:
            return self.communities.get(name)
        except KeyError:
            return None

    def create_widgets(self):
        # 显示好友功能
        tk.Label(self.root, text="Enter username to display friends:").grid(row=0, column=0, padx=10, pady=5)
        self.display_friends_entry = tk.Entry(self.root)
        self.display_friends_entry.grid(row=0, column=1, padx=10, pady=5)
        tk.Button(self.root, text="Display Friends", command=self.display_friends).grid(row=0, column=2, padx=10, pady=5)

        # 添加好友功能
        tk.Label(self.root, text="Add friend (Username):").grid(row=1, column=0, padx=10, pady=5)
        self.add_friend_user_entry = tk.Entry(self.root)
        self.add_friend_user_entry.grid(row=1, column=1, padx=10, pady=5)
        tk.Label(self.root, text="Friend's Username:").grid(row=2, column=0, padx=10, pady=5)
        self.add_friend_friend_entry = tk.Entry(self.root)
        self.add_friend_friend_entry.grid(row=2, column=1, padx=10, pady=5)
        tk.Button(self.root, text="Add Friend", command=self.add_friend).grid(row=2, column=2, padx=10, pady=5)

        # 根据兴趣过滤用户功能
        tk.Label(self.root, text="Filter by Interest:").grid(row=3, column=0, padx=10, pady=5)
        self.filter_interest_entry = tk.Entry(self.root)
        self.filter_interest_entry.grid(row=3, column=1, padx=10, pady=5)
        tk.Button(self.root, text="Filter Users", command=self.filter_users_by_criteria).grid(row=3, column=2, padx=10, pady=5)

        # 创建社区功能
        tk.Label(self.root, text="Create Community (Name):").grid(row=4, column=0, padx=10, pady=5)
        self.create_community_name_entry = tk.Entry(self.root)
        self.create_community_name_entry.grid(row=4, column=1, padx=10, pady=5)
        tk.Label(self.root, text="Description:").grid(row=5, column=0, padx=10, pady=5)
        self.create_community_description_entry = tk.Entry(self.root)
        self.create_community_description_entry.grid(row=5, column=1, padx=10, pady=5)
        tk.Label(self.root, text="Topic:").grid(row=6, column=0, padx=10, pady=5)
        self.create_community_topic_entry = tk.Entry(self.root)
        self.create_community_topic_entry.grid(row=6, column=1, padx=10, pady=5)
        tk.Button(self.root, text="Create Community", command=self.create_community).grid(row=6, column=2, padx=10, pady=5)

        # 添加社区成员功能
        tk.Label(self.root, text="Add Member to Community (Community Name):").grid(row=7, column=0, padx=10, pady=5)
        self.add_member_community_entry = tk.Entry(self.root)
        self.add_member_community_entry.grid(row=7, column=1, padx=10, pady=5)
        tk.Label(self.root, text="Member Username:").grid(row=8, column=0, padx=10, pady=5)
        self.add_member_username_entry = tk.Entry(self.root)
        self.add_member_username_entry.grid(row=8, column=1, padx=10, pady=5)
        tk.Button(self.root, text="Add Member", command=self.add_member_to_community).grid(row=8, column=2, padx=10, pady=5)

        # 显示社区成员功能
        tk.Label(self.root, text="Show Members of Community (Community Name):").grid(row=9, column=0, padx=10, pady=5)
        self.show_members_community_entry = tk.Entry(self.root)
        self.show_members_community_entry.grid(row=9, column=1, padx=10, pady=5)
        tk.Button(self.root, text="Show Members", command=self.show_community_members).grid(row=9, column=2, padx=10, pady=5)

        # 输出窗口
        self.output_text = tk.Text(self.root, height=10, width=50)
        self.output_text.grid(row=10, column=0, columnspan=3, padx=10, pady=5)

    def display_friends(self):
        username = self.display_friends_entry.get()
        student = self.find_student_by_username(username)
        if student:
            friends = ", ".join([self.find_student_by_username(friend).full_name for friend in student.relations])
            self.output_text.delete(1.0, tk.END)
            self.output_text.insert(tk.END, f"Friends of {username}: {friends}")
        else:
            messagebox.showerror("Error", f"User '{username}' not found!")

    def add_friend(self):
        user = self.add_friend_user_entry.get()
        friend = self.add_friend_friend_entry.get()
        student = self.find_student_by_username(user)
        friend_student = self.find_student_by_username(friend)
        if student and friend_student:
            student.add_friend(friend)
            messagebox.showinfo("Success", f"Added '{friend}' as a friend of '{user}'.")
        else:
            messagebox.showerror("Error", "Invalid username(s)!")

    def filter_users_by_criteria(self):
        interest = self.filter_interest_entry.get().strip()
        filtered_users = [student for student in self.students.buckets if student and interest in student.interests]
        if filtered_users:
            result = "\n".join([f"{student.full_name} ({student.username})" for student in filtered_users])
            self.output_text.delete(1.0, tk.END)
            self.output_text.insert(tk.END, f"Users interested in '{interest}':\n{result}")
        else:
            messagebox.showinfo("Info", f"No users found with interest '{interest}'.")

    def create_community(self):
        name = self.create_community_name_entry.get().strip()
        description = self.create_community_description_entry.get().strip()
        topic = self.create_community_topic_entry.get().strip()
        if name and description and topic:
            if not self.find_community_by_name(name):
                self.communities.insert(name, Community(name=name, description=description, topic=topic))
                messagebox.showinfo("Success", f"Community '{name}' created successfully!")
            else:
                messagebox.showerror("Error", f"Community '{name}' already exists!")
        else:
            messagebox.showerror("Error", "Please fill in all fields!")

    def add_member_to_community(self):
        community_name = self.add_member_community_entry.get().strip()
        username = self.add_member_username_entry.get().strip()
        community = self.find_community_by_name(community_name)
        student = self.find_student_by_username(username)
        if community and student:
            community.add_member(username)
            student.join_community(community_name)
            messagebox.showinfo("Success", f"User '{username}' added to community '{community_name}'.")
        elif not community:
            messagebox.showerror("Error", f"Community '{community_name}' not found!")
        elif not student:
            messagebox.showerror("Error", f"User '{username}' not found!")

    def show_community_members(self):
        community_name = self.show_members_community_entry.get().strip()
        community = self.find_community_by_name(community_name)
        if community:
            members_info = [self.find_student_by_username(member).full_name for member in community.members if self.find_student_by_username(member)]
            if members_info:
                result = "\n".join(members_info)
                self.output_text.delete(1.0, tk.END)
                self.output_text.insert(tk.END, f"Members of '{community_name}':\n{result}")
            else:
                self.output_text.delete(1.0, tk.END)
                self.output_text.insert(tk.END, f"No members found in community '{community_name}'.")
        else:
            messagebox.showerror("Error", f"Community '{community_name}' not found!")

if __name__ == "__main__":
    root = tk.Tk()
    app = SocialNetworkApp(root)
    root.mainloop()